#!/usr/bin/env node
const express = require('express');
const bodyParser = require('body-parser');
const WSServer = require('ws').Server;
const request = require('superagent');

function startServer(port) {
    const html = `
    <head>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
    <script src="plotly/plotly.min.js"></script>
    </head>
    <body>
    <div id="main" style="width:1000px;height:600px;" />
    <script>
    var el = document.getElementById("main");
    var ws = new WebSocket("ws://localhost:${port+1}");
    ws.onopen = function () {
        console.log('connet to server');
    }
    ws.onmessage = function (e) {
        var data = JSON.parse(e.data);
        console.log('[recv]:', data);
        data.type ? Plotly.newPlot(el, data.data) : Plotly.plot(el, data.data);
    }
    </script>
    </body>
    </html>
    `;
    let wsclient;
    const app = express();
    const server = app.listen(port);
    app.use(bodyParser.json());
    app.use(express.static(__dirname+'/static'));

    app.get('/plot', function(req, res){
        res.send(html);
    });
    app.post('/draw', function(req, res){
        console.log('[draw]:', req.body.data);
        wsclient.send(JSON.stringify(req.body));
        res.send('success');
    });
    server.on('listening', function () {
        const url = `http://localhost:${port}/plot`;
        console.log(url);
        const wss = new WSServer({ port: port+1 });
        wss.on('connection', function (ws) {
            console.log("client connection");
            wsclient = ws;
        });
    });
}
function draw(data, type = 0) {
    request
    .post(`http://localhost:5000/draw`)
    .set({ 'Content-Type': 'application/json' })
    .send({ data, type })
    .end((error, res) => {
        console.log('draw success');
    });
}

var param = process.argv[2];
if (param === '-h' || param === '--help') {
    console.log('');
    console.log('xplot opts');
    console.log('');
    console.log('   -h|--help: show help');
    console.log('   -s|--server: start a plot server');
    console.log('   -d|--draw [data]: draw plot graph');
    console.log('');
} else if (param === '-s' || param === '--server') {
    startServer(5000);
} else if (param === '-d' || param === '--draw') {
    console.log('[draw]:', process.argv[3]);
    const data = (new Function(`return ${process.argv[3]}`))();
    draw(data, process.argv[4]);
}
module.exports = {
    draw,
};
